﻿using System;
using System.Linq;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using TelerikedIn.Data;
using TelerikedIn.WebApp.ViewModels.Connections;
using TelerikedIn.WebApp.ViewModels.User;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
using Newtonsoft.Json;

namespace TelerikedIn.WebApp.Controllers
{
    [Authorize]
    public class ConnectionsController : Controller
    {
        private UowData data;

        public ConnectionsController() 
            : this(new UowData())
        {
        }

        public ConnectionsController(UowData data)
        {
            this.data = data;
        }

        // Get /Connections/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Read([DataSourceRequest]DataSourceRequest request)
        {
            try
            {
                var connectionsUsers = GetConnectionsAndEndorsments();
                
                return Json(connectionsUsers.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Content("A database connection error occured");
            }
        }

        public ActionResult SearchUser(string searchQuery)
        {
            searchQuery = Server.UrlDecode(searchQuery);
            try
            {
                var currentUserId = User.Identity.GetUserId();

                var connections = this.data.Connections.All()
                    .Where(c => c.ToUserId == currentUserId);

                var users = this.data.Users.All()
                    .Where(u => 
                        u.Id != currentUserId &&
                        !connections.Any(con => con.FromUserId == u.Id) &&
                       (u.UserName.Contains(searchQuery) ||
                        u.FirstName.Contains(searchQuery) ||
                        u.LastName.Contains(searchQuery)))
                    .OrderBy(user => user.FirstName)
                    .ThenBy(user => user.LastName)
                    .Select(UserVM.FromUser);

                return PartialView(users);
            }
            catch 
            {
                return Content("No users matching that search and NOT connected already found!");
            }
        }

        public ActionResult AddUser(string id)
        {
            try
            {
                var currentUserId = User.Identity.GetUserId();
                this.data.Connections.Add(new Models.Connection { FromUserId = currentUserId, ToUserId = id });
                this.data.Connections.Add(new Models.Connection { FromUserId = id, ToUserId = currentUserId });
                this.data.SaveChanges();
                return Content("Added succesfully");
            }
            catch
            {
                return Content("Couldn't add this user as a connection. Perhaps you are already connected?");
            }
        }

        private IQueryable<ConnectionsVM> GetConnectionsAndEndorsments()
        {
            var currentUserId = User.Identity.GetUserId();

            //take all connetions that current user has
            var connections = this.data.Connections.All().Where(c => c.ToUserId == currentUserId);
            
            // take users connected to current user and their skills
            var connectionsUsers = this.data.Users
                                       .All(new [] {"Skills"})
                                       .Where(u => connections.Any(con => con.FromUserId == u.Id))
                                       .Select(ConnectionsVM.FromUser);
            
            ////take all endrosments that curren user has made
            //var endorsmentsForUsers = this.data.Endorsments.All().Where(e => e.ByUserId == userId);

            //// if the current user has already endorsed some user for some skill
            //// this skill will be marked IsEndorsed!
            //foreach (var otherUser in connectionsUsers)
            //{
            //    foreach (var skill in otherUser.Skills)
            //    {
            //        if (endorsmentsForUsers.Any(e => e.SkillId == skill.Id && e.ForUserId == otherUser.UserId))
            //        {
            //            skill.IsEndorsed = true;
            //        }
            //    }
            //}
            return connectionsUsers;
        }
    }
}